- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathmatrix-exponentiation.cpp
48 lines (42 loc) · 1.12 KB
/
matrix-exponentiation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// { Driver Code Starts
#include<bits/stdc++.h>
usingnamespacestd;
// } Driver Code Ends
classSolution {
private:int M = 1000000007;
vector<vector<longlongint>> multi(vector<vector<longlongint>> &a, vector<vector<longlongint>> &b) {
vector<vector<longlongint>> c = {{0,0},{0,0}};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
c[i][j] += ((a[i][k]%M)*(b[k][j]%M))%M;
}
}
}
return c;
}
public : intFindNthTerm(longlongint n) {
vector<vector<longlongint>> mat = {{1,1},{1,0}};
vector<vector<longlongint>> res = {{1,1},{1,0}};
while(n) {
if(n%2 == 1)
res = multi(mat,res);
mat = multi(mat,mat);
n = n>>1;
}
return res[0][1]%M;
}
};
// { Driver Code Starts.
intmain(){
int tc;
cin >> tc;
while(tc--){
longlongint n;
cin >> n;
Solution obj;
int ans = obj.FindNthTerm(n);
cout << ans << "\n";
}
return0;
} // } Driver Code Ends